package com.zrwl.poscloud.xo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrwl.poscloud.base.entity.Admin;
import com.zrwl.poscloud.base.entity.CompanyAdminR;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.holder.RequestHolder;
import com.zrwl.poscloud.commons.utils.HTTPUtils;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.xo.global.MessageConf;
import com.zrwl.poscloud.xo.global.SQLConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.mapper.CompanyAdminRMapper;
import com.zrwl.poscloud.xo.service.AdminRoleService;
import com.zrwl.poscloud.xo.service.AdminService;
import com.zrwl.poscloud.xo.service.CompanyAdminRService;
import com.zrwl.poscloud.xo.service.CompanyService;
import com.zrwl.poscloud.xo.vo.AdminRoleVO;
import com.zrwl.poscloud.xo.vo.AdminVO;
import com.zrwl.poscloud.xo.vo.CompanyAdminRVO;
import org.apache.http.client.config.RequestConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商户管理员 服务实现类
 *
 * @author 刘思童 AutoGenerate
 * @date 2021-02-25
 */
@Service
public class CompanyAdminRServiceImpl extends SuperServiceImpl<CompanyAdminRMapper, CompanyAdminR> implements CompanyAdminRService {

//    @Autowired
//    private RequestConfig requestConfig;
    @Autowired
    private CompanyAdminRService companyAdminRService;
    @Resource
    private CompanyAdminRMapper companyAdminRMapper;
    @Autowired
    private CompanyService companyService;
    @Resource
    private AdminService adminService;
    @Resource
    private AdminRoleService adminRoleService;
//    @Autowired
//    private ServerSyncRecordService serverSyncRecordService;

    @Override
    public IPage<CompanyAdminRVO> getPageList(CompanyAdminRVO companyAdminRVO) {
        Page<CompanyAdminR> page = new Page<>();
        page.setCurrent(companyAdminRVO.getCurrentPage());
        page.setSize(companyAdminRVO.getPageSize());
        IPage<CompanyAdminRVO> pageList = companyAdminRMapper.getList(page, companyAdminRVO);
        List<CompanyAdminRVO> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public IPage<CompanyAdminRVO> getCompanyAdminList(CompanyAdminRVO companyAdminRVO) {
        HttpServletRequest request = RequestHolder.getRequest();
        String ownerUid = null;
        if (request.getAttribute(SysConf.OWNER_UID) != null) {
            ownerUid = request.getAttribute(SysConf.OWNER_UID).toString();
            companyAdminRVO.setCompanyUid(ownerUid);
        }
        Page<CompanyAdminR> page = new Page<>();
        page.setCurrent(companyAdminRVO.getCurrentPage());
        page.setSize(companyAdminRVO.getPageSize());
        IPage<CompanyAdminRVO> pageList = companyAdminRMapper.getCompanyAdminList(page, companyAdminRVO);
        List<CompanyAdminRVO> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<CompanyAdminR> getAllList(CompanyAdminRVO companyAdminRVO) {
        QueryWrapper<CompanyAdminR> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        List<CompanyAdminR> list = companyAdminRService.list(queryWrapper);
        return list;
    }


    @Override
    public List<CompanyAdminRVO> getMyCompanyList() {
        Page<CompanyAdminR> page = new Page<>();
        page.setCurrent(1);
        page.setSize(SQLConf.MAX_PAGESIZE);
        CompanyAdminRVO companyAdminRVO = new CompanyAdminRVO();
        companyAdminRVO.setAdminUid(adminService.getMe().getUid());
        IPage<CompanyAdminRVO> pageList = companyAdminRMapper.getList(page, companyAdminRVO);
        List<CompanyAdminRVO> list = pageList.getRecords();
        for (CompanyAdminRVO items : list) {
            items.setAdminRoleVOList(adminRoleService.getComMerMatchRoleList(items.getCompanyUid()));
        }
        return list;
    }
//
//    @Override
//    public String add(CompanyAdminRVO companyAdminRVO) {
//        HttpServletRequest request = RequestHolder.getRequest();
//        String ownerUid = null;
//        Integer ownerType = null;
//        if (request.getAttribute(SysConf.OWNER_UID) != null) {
//            ownerUid = request.getAttribute(SysConf.OWNER_UID).toString();
//            ownerType = (Integer) request.getAttribute(SysConf.OWNER_TYPE);
//        }
//        QueryWrapper<CompanyAdminR> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("admin_uid", companyAdminRVO.getAdminUid());
//        if (companyAdminRVO.getCompanyUid() != null) {
//            queryWrapper.eq("company_uid", companyAdminRVO.getCompanyUid());
//        } else {
//            queryWrapper.eq("company_uid", ownerUid);
//        }
//        CompanyAdminR temp = companyAdminRService.getOne(queryWrapper);
//        if (temp == null) {
//            CompanyAdminR entity = new CompanyAdminR();
//            BeanUtils.copyProperties(companyAdminRVO, entity, SysConf.STATUS);
//            if (companyAdminRVO.getCompanyUid() != null) {
//                Admin admin = adminService.getById(companyAdminRVO.getAdminUid());
//                admin.setDefaultUid(companyAdminRVO.getCompanyUid());
//                admin.setOwnerType(2);
//                admin.updateById();
//                ServerSyncRecordVO serverSyncRecordVO = new ServerSyncRecordVO();//加入同步数据
//                serverSyncRecordVO.setObject(admin);
//                serverSyncRecordVO.setCompanyUid(admin.getDefaultUid());
//                serverSyncRecordVO.setSummary(CompanyServerBusinessType.adminInformationDown.getName());
//                serverSyncRecordVO.setName(CompanyServerBusinessType.adminInformationDown.getName());
//                serverSyncRecordVO.setType(CompanyServerBusinessType.adminInformationDown.getServerBusinessType());
//                serverSyncRecordService.add(serverSyncRecordVO);
//            }
//            if (companyAdminRVO.getCompanyCode() == null && companyAdminRVO.getCompanyUid() == null) {
//                entity.setCompanyUid(ownerUid);
//                entity.setCompanyCode(companyService.getById(ownerUid).getCompanyCode());
//                Admin admin = adminService.getById(companyAdminRVO.getAdminUid());
//                admin.setDefaultUid(ownerUid);
//                admin.setOwnerType(ownerType);
//                admin.updateById();
//                ServerSyncRecordVO serverSyncRecordVO = new ServerSyncRecordVO();//加入同步数据
//                serverSyncRecordVO.setObject(admin);
//                serverSyncRecordVO.setCompanyUid(admin.getDefaultUid());
//                serverSyncRecordVO.setSummary(CompanyServerBusinessType.adminInformationDown.getName());
//                serverSyncRecordVO.setName(CompanyServerBusinessType.adminInformationDown.getName());
//                serverSyncRecordVO.setType(CompanyServerBusinessType.adminInformationDown.getServerBusinessType());
//                serverSyncRecordService.add(serverSyncRecordVO);
//            }
//            entity.setCreateAdminUid(adminService.getMe().getUid());
//            entity.insert();
//            ServerSyncRecordVO serverSyncRecordVO = new ServerSyncRecordVO();//加入同步数据
//            serverSyncRecordVO.setObject(entity);
//            serverSyncRecordVO.setCompanyUid(entity.getCompanyUid());
//            if (companyAdminRVO.getCompanyUid() != null) {//这个值存在则证明是非商户管理员创建的
//                serverSyncRecordVO.setSummary(CompanyServerBusinessType.companyAdminRInformationDown.getName());
//                serverSyncRecordVO.setName(CompanyServerBusinessType.companyAdminRInformationDown.getName());
//                serverSyncRecordVO.setType(CompanyServerBusinessType.companyAdminRInformationDown.getServerBusinessType());
//            } else {
//                serverSyncRecordVO.setSummary(CompanyServerBusinessType.companyAdminRInformationUpload.getName());
//                serverSyncRecordVO.setName(CompanyServerBusinessType.companyAdminRInformationUpload.getName());
//                serverSyncRecordVO.setType(CompanyServerBusinessType.companyAdminRInformationUpload.getServerBusinessType());
//            }
//            serverSyncRecordService.add(serverSyncRecordVO);
//            return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
//        } else {
//            return ResultUtil.errorWithMessage("重复添加权限!");
//        }
//    }

    @Override
    public String edit(CompanyAdminRVO companyAdminRVO) {
        CompanyAdminR entity = companyAdminRService.getById(companyAdminRVO.getUid());
        BeanUtils.copyProperties(companyAdminRVO, entity);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String delete(CompanyAdminRVO companyAdminRVO) {
        CompanyAdminR entity = companyAdminRService.getById(companyAdminRVO.getUid());
        entity.setStatus(EStatus.DISABLED);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

//    @Override
//    public String roleSwitch(CompanyAdminRVO companyAdminRVO) {
//        CompanyAdminR entity = companyAdminRService.getById(companyAdminRVO.getUid());
//        if (companyAdminRVO.getStatus() == 0) {
//            entity.setStatus(EStatus.ENABLE);
//            //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
//        } else {
//            entity.setStatus(EStatus.DISABLED);
//            //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
//        }
//        entity.updateById();
//        AdminVO adminVO = adminService.getMe();
//        ServerSyncRecordVO serverSyncRecordVO = new ServerSyncRecordVO();//加入同步数据
//        serverSyncRecordVO.setObject(entity);
//        serverSyncRecordVO.setCompanyUid(entity.getCompanyUid());
//        if (adminVO.getOwnerUid().equals(entity.getCompanyUid())) {
//            serverSyncRecordVO.setSummary(CompanyServerBusinessType.companyAdminRInformationUpload.getName());
//            serverSyncRecordVO.setName(CompanyServerBusinessType.companyAdminRInformationUpload.getName());
//            serverSyncRecordVO.setType(CompanyServerBusinessType.companyAdminRInformationUpload.getServerBusinessType());
//        } else {
//            serverSyncRecordVO.setSummary(CompanyServerBusinessType.companyAdminRInformationDown.getName());
//            serverSyncRecordVO.setName(CompanyServerBusinessType.companyAdminRInformationDown.getName());
//            serverSyncRecordVO.setType(CompanyServerBusinessType.companyAdminRInformationDown.getServerBusinessType());
//        }
//        serverSyncRecordService.add(serverSyncRecordVO);
//        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
//    }

    @Override
    public IPage<CompanyAdminRVO> getCompanyAdminList(AdminRoleVO adminRoleVO) {
        Page<CompanyAdminR> page = new Page<>();
        page.setCurrent(adminRoleVO.getCurrentPage());
        page.setSize(adminRoleVO.getPageSize());
        IPage<CompanyAdminRVO> pageList = companyAdminRMapper.getAdminCompanyList(page, adminRoleVO.getAdminUid());
        List<CompanyAdminRVO> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public IPage<CompanyAdminRVO> getPresentCompanyAdminList(CompanyAdminRVO companyAdminRVO) {
        HttpServletRequest request = RequestHolder.getRequest();
        String ownerUid = null;
        Integer ownerType = null;
        if (request.getAttribute(SysConf.OWNER_UID) != null) {
            ownerUid = request.getAttribute(SysConf.OWNER_UID).toString();
            ownerType = (Integer) request.getAttribute(SysConf.OWNER_TYPE);
        }
        if (ownerUid != null && ownerType == 2) {
            Page<CompanyAdminR> page = new Page<>();
            page.setCurrent(companyAdminRVO.getCurrentPage());
            page.setSize(companyAdminRVO.getPageSize());
            companyAdminRVO.setCompanyUid(ownerUid);
            IPage<CompanyAdminRVO> pageList = companyAdminRMapper.getPresentCompanyAdminList(page, companyAdminRVO);
            List<CompanyAdminRVO> list = pageList.getRecords();
            pageList.setRecords(list);
            return pageList;
        } else {
            return null;
        }
    }

    @Override
    public List<CompanyAdminRVO> getPushAbleAdminInfoList(CompanyAdminRVO companyAdminRVO) {
        return companyAdminRMapper.getPushAbleAdminInfoList(companyAdminRVO);
    }

//    @Override
//    @Transactional
//    public String localAdd(CompanyAdminRVO companyAdminRVO) {
//        HttpServletRequest request = RequestHolder.getRequest();
//        String ownerUid = null;
//        if (request.getAttribute(SysConf.OWNER_UID) != null) {
//            ownerUid = request.getAttribute(SysConf.OWNER_UID).toString();
//        }
//        QueryWrapper<CompanyAdminR> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("admin_uid", companyAdminRVO.getAdminUid());
//        if (companyAdminRVO.getCompanyUid() != null) {
//            queryWrapper.eq("company_uid", companyAdminRVO.getCompanyUid());
//        } else {
//            queryWrapper.eq("company_uid", ownerUid);
//        }
//        CompanyAdminR temp = companyAdminRService.getOne(queryWrapper);
//        if (temp == null) {
//            try {
//                JSONObject jsonObject = new JSONObject();
//                if (companyAdminRVO.getCompanyCode() == null && companyAdminRVO.getCompanyUid() == null) {
//                    jsonObject.put("companyUid", ownerUid);
//                    jsonObject.put("companyCode", companyService.getById(ownerUid).getCompanyCode());
//                } else {
//                    jsonObject.put("companyUid", companyAdminRVO.getCompanyUid());
//                    jsonObject.put("companyCode", companyAdminRVO.getCompanyCode());
//                }
//                jsonObject.put("adminUid", companyAdminRVO.getAdminUid());
//                jsonObject.put("createAdminUid", adminService.getMe().getUid());
//                jsonObject.put("type", 3);
//                String address = requestConfig.cloudUrl + requestConfig.VerifyNewCreateAdminOrRoleUrl;
//                Map<String, String> params = new HashMap<>();
//                params.put("jsonStr", JSONObject.toJSONString(jsonObject));
//                String res = HTTPUtils.post(address, params, null);
//                res = res.substring(res.indexOf("{"));//截取
//                String code = JSONObject.parseObject(res).getString("code");
//                if (code.equals("success")) {
//                    CompanyAdminR entity = JSONObject.parseObject(JSONObject.parseObject(res).getString("data"), CompanyAdminR.class);
//                    entity.insertOrUpdate();
//                    Admin admin = adminService.getById(entity.getAdminUid());
//                    admin.setDefaultUid(entity.getCompanyUid());
//                    admin.setOwnerType(2);
//                    admin.updateById();
//                    log.debug("商户管理员创建完成" + "time:" + new Date());
//                } else {
//                    throw new RuntimeException(JSONObject.parseObject(res).getString("message"));
//                }
//            } catch (Exception e) {
//                log.error(e.getMessage() + new Date());
//                throw new RuntimeException(e.getMessage());
//            }
//            return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
//        } else {
//            return ResultUtil.errorWithMessage("重复添加权限!");
//        }
//    }

   /* @Override
    public List batchAdd(List<Map<String, String>> list, String superCompanyCode) {
        List<Map> errorList = new ArrayList<Map>();
        List<CompanyAdminRVO> successList = new ArrayList<CompanyAdminRVO>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, String> row = list.get(i);
            CompanyAdminRVO companyAdminRVO = new CompanyAdminRVO();
            if (StringUtils.isEmpty(row.get("姓名"))) {
                row.put("失败原因", "姓名不能为空");
                errorList.add(row);
                break;
            } else {
                companyAdminRVO.setCompanyName(row.get("姓名"));

            }
            if (StringUtils.isEmpty(row.get("所属机构"))) {
                row.put("失败原因", "所属机构不能为空");
                errorList.add(row);
                break;
            } else {
                companyAdminRVO.setCompanyName(row.get("所属机构"));
                for (CompanyAdminRVO companyAdminRvo : companyAdminRService.getMyCompanyList()) {
                    if (superCompanyCode.equals(companyAdminRvo.getCompanyCode())) {
                        List<CompanyAdminRVO> companyAdminRVOList = new ArrayList<>();
                        companyAdminRVOList.add(companyAdminRvo);
                        DeptVO deptVO = new DeptVO();
                        deptVO.setMyCompanyList(companyAdminRVOList);
                        for (Dept dept:deptService.getAllList(deptVO)) {
                            if (row.get("所属机构").equals(dept.getName())) {
                                companyAdminRvo.setCompanyCode(dept.getCompanyCode());
                            }
                        }

                    }

                }
            }
        }




*/



      /*  DeptVO deptVo = new DeptVO();
        deptVo.setMyCompanyList(companyAdminRService.getMyCompanyList());
        List<Dept> arryList = deptService.getAllList(deptVo);
        for (int i = 1; i < list.size(); i++) {
            for (Dept dep : arryList) {
                if (list.get(i).size() > 1) {
                    if (list.get(i).get(0) != null && list.get(i).get(0).equals(dep.getName())) {
                        list.remove(i);
                       // list.get(i).remove(dep.getName());
                        //new CompanyAdminRServiceImpl().batchAdd(list,superCompanyCode,companyService,deptService);
                    }
                }
            }
        }
        for (int i = 1; i < list.size(); i++) {
            for (CompanyAdminRVO companyAdminRvo : companyAdminRService.getMyCompanyList()) {
                if (superCompanyCode.equals(companyAdminRvo.getCompanyCode())) {
                    DeptVO deptVO2 = new DeptVO();
                    deptVO2.setMyCompanyList(companyAdminRService.getMyCompanyList());
                    List<Dept> aList = deptService.getAllList(deptVO2);
                    for (Dept dep : aList) {
                        if (list.get(i).size() > 1 && !list.get(i).isEmpty()) {
                            if (list.get(i).get(1).equals(companyAdminRvo.getCompanyName())) {
                                DeptVO deptVO = new DeptVO();
                                deptVO.setName(list.get(i).get(0));
                                deptVO.setSuperCompanyCode(superCompanyCode);
                                Company company = companyService.getByCode(deptVO.getSuperCompanyCode().substring(0, 5));
                                deptVO.setCompanyUid(company.getUid());
                                deptService.add(deptVO);
                                System.out.println(deptVO.toString());
                                list.remove(i);
                                //new CompanyAdminRServiceImpl().batchAdd(list,superCompanyCode,companyService,deptService);
                            }
                        }
                    }
                }
            }
        }
        for (int i = 1; i < list.size(); i++) {
            for (CompanyAdminRVO companyAdminRvo : companyAdminRService.getMyCompanyList()) {
                if (superCompanyCode.equals(companyAdminRvo.getCompanyCode())) {
                    DeptVO deptVO2 = new DeptVO();
                    deptVO2.setMyCompanyList(companyAdminRService.getMyCompanyList());
                    List<Dept> aList = deptService.getAllList(deptVO2);
                    for (Dept dep : aList) {
                        DeptVO deptVO = new DeptVO();
                        deptVO.setMyCompanyList(companyAdminRService.getMyCompanyList());
                        List<Dept> allList = deptService.getAllList(deptVO);
                        for (Dept dept : allList) {
                            if (list.get(i).size() > 1 && !list.get(i).isEmpty()) {
                                if (list.get(i).get(1).equals(dept.getName())) {
                                    DeptVO deptV = new DeptVO();
                                    deptV.setName(list.get(i).get(0));
                                    deptV.setSuperCompanyCode(dept.getCompanyCode());
                                    Company company = companyService.getByCode(deptV.getSuperCompanyCode().substring(0, 5));
                                    deptV.setCompanyUid(company.getUid());
                                    deptService.add(deptV);
                                    System.out.println(deptV.toString());
                                    list.remove(i);
                                    //new CompanyAdminRServiceImpl().batchAdd(list,superCompanyCode,companyService,deptService);
                                }
                            }
                        }
                    }
                }
            }
        }*/
  /*      return errorList;
    }*/
}
